package com.sskj.mine;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.allen.library.SuperTextView;
import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.shizhefei.view.coolrefreshview.SimpleOnPullListener;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.router.provider.LogoutProvider;
import com.sskj.lib.util.AppDirectCheckUtil;
import com.sskj.lib.util.AppOuterCheckUtil;
import com.sskj.mine.account.AccountManagerActivity;
import com.sskj.mine.component.DaggerUserDataComponent;
import com.sskj.mine.dialog.TipDialog;
import com.sskj.mine.invite.InviteActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * @author Hey
 * Create at  2019/05/01
 */
@Route(path = RConfig.MINE_FRAGMENT_MAIN)
public class MineFragment extends BaseFragment<MinePresenter> {

    @BindView(R2.id.user_head_img)
    ImageView userHeadImg;
    @BindView(R2.id.name_tv)
    TextView nameTv;
    @BindView(R2.id.user_slogan)
    TextView userSlogan;
    @BindView(R2.id.user_id)
    TextView userId;
    @BindView(R2.id.menu_person)
    SuperTextView menuPerson;
    @BindView(R2.id.menu_security)
    SuperTextView menuSecurity;
    @BindView(R2.id.menu_payment)
    SuperTextView menuPayment;
    @BindView(R2.id.menu_invite)
    SuperTextView menuInvite;
    @BindView(R2.id.menu_seller)
    SuperTextView menuSeller;
    @BindView(R2.id.menu_account)
    SuperTextView menuAccount;
    @BindView(R2.id.menu_setting)
    SuperTextView menuSetting;
    @BindView(R2.id.menu_node)
    SuperTextView menuNode;
    @BindView(R2.id.logout_btn)
    Button logoutBtn;
    @BindView(R2.id.coolRefreshView)
    CoolRefreshView coolRefreshView;
    @BindView(R2.id.mine_gonggao)
    TextView mineGg;  // 公告
    private String imgFirst;
    private UserData mUserData;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;

    @Override
    public int getLayoutId() {
        return R.layout.mine_fragment_mine;
    }

    @Override
    public MinePresenter getPresenter() {
        return new MinePresenter();
    }

    @Override
    public void initView() {
        RxBus.getDefault().register(this);
        coolRefreshView.addOnPullListener(new SimpleOnPullListener() {
            @Override
            public void onRefreshing(CoolRefreshView refreshView) {
                mPresenter.requestUserInfo();
            }
        });
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    protected void initEvent() {
        // 公告
        ClickUtil.click(mineGg, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            ARouter.getInstance().build(RConfig.APP_GONGGAO_LIST).navigation();
        });
        // 设置头像
        ClickUtil.click(userHeadImg, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            selectImage(1);
        });
        //个人中心
        ClickUtil.click(menuPerson, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            PersonActivity.start(getContext());
        });
        //安全中心
        ClickUtil.click(menuSecurity, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            SecurityActivity.start(getContext());
        });
        //收款方式
        ClickUtil.click(menuPayment, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            PaymentActivity.start(getContext());
        });
        //超级节点
        ClickUtil.click(menuNode, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            if (mUserData.getIs_jd() == 0) {
                ToastUtil.showShort(getString(R.string.mine_no_root_privalage));
                return;
            }
            SuperNodeActivity.start(getContext());
        });
        //邀请返佣
        ClickUtil.click(menuInvite, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {
                return;
            }
            InviteActivity.start(getContext());
        });
        //商家认证
        ClickUtil.click(menuSeller, () -> {  //  0否 1是 2申请商家审核中 3撤销商家审核中
            if (!AppOuterCheckUtil.checkHighAuth(getActivity(), mUserData)) {  // 高级认证
                return;
            }
            if (mUserData.getIs_shop().equals("0")) {  // 不是商家
                SellerApplyActivity.start(getContext());
                return;
            }
            if (mUserData.getIs_shop().equals("2")) {  // 认证商家待审核
                ToastUtil.showShort(getString(R.string.mine_mineFragment1));
                return;
            }
            if (mUserData.getIs_shop().equals("3")) {  // 解除商家待审核
                ToastUtil.showShort(getString(R.string.mine_mineFragment1));
                return;
            }
            new TipDialog(getContext())
                    .setContent(getString(R.string.mine_mineFragment2))
                    .setCancelButtonText(getString(R.string.mine_mineFragment3))
                    .setTitle(getString(R.string.mine_mineFragment4))
                    .setConfirmButtonText(getString(R.string.mine_mineFragment5))
                    .setListener(dialog -> {
                        dialog.dismiss();
                        mPresenter.cancelShop();
                    })
                    .show();
        });
        //账号管理
        ClickUtil.click(menuAccount, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {  // 登录
                return;
            }
            AccountManagerActivity.start(getContext());
        });
        //设置
        ClickUtil.click(menuSetting, () -> {
            if (!AppDirectCheckUtil.checkLogin(getActivity(), mUserData)) {  // 登录
                return;
            }
            SettingActivity.start(getContext());
        });
        //退出登录
        ClickUtil.click(logoutBtn, () -> {
            new TipDialog(getActivity())
                    .setContent(getString(R.string.mine_mineFragment6))
                    .setConfirmButtonText(getString(R.string.mine_mineFragment7))
                    .setListener(dialog -> {
                        dialog.dismiss();
                        LogoutProvider logoutProvider = ARouter.getInstance().navigation(LogoutProvider.class);
                        logoutProvider.logout();
                    }).show();
        });


    }

    public static MineFragment newInstance() {
        MineFragment fragment = new MineFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    public void updateUserTitle(UserData userData) {
        mUserData = userData;
        ImageUtil.setCircleImage(TextUtils.isEmpty(userData.getUpic()) ? getResources().getDrawable(R.mipmap.mine_user_head) : userData.getUpic(), userHeadImg);
        nameTv.setText(TextUtils.isEmpty(userData.getNickname()) ? "----" : "" + userData.getNickname());
        userId.setText("UID: " + userData.getAccount());
        userSlogan.setText(userData.getGrade());
        if (coolRefreshView != null && coolRefreshView.isRefreshing()) {
            coolRefreshView.setRefreshing(false);
        }
    }

    public void uploadFail() {
        Glide.with(this).load(getResources().getDrawable(R.mipmap.mine_user_head)).into(userHeadImg);
    }

    public void putList(String url) {
        imgFirst = url;
    }

    @SuppressLint("CheckResult")
    private void selectImage(int requestCode) {
        new RxPermissions(getActivity())
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(granted -> {
                    if (granted) {
                        PictureSelector.create(this)
                                .openGallery(PictureMimeType.ofImage())
                                .previewImage(true)
                                .isCamera(true)
                                .imageFormat(PictureMimeType.JPEG)
                                .maxSelectNum(1)
                                .compress(true)
                                .forResult(requestCode);
                    }
                });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onResultPicture(Intent data) {
        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
        if (selectList != null && selectList.size() > 0) {
            LocalMedia media = selectList.get(0);
            String url;
            if (media.isCompressed()) {
                url = media.getCompressPath();
            } else {
                url = media.getPath();
            }
            ImageUtil.setCircleImage(url, userHeadImg);
            mPresenter.submitVerify(new File(url));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.requestUserInfo();
        if (userViewModel != null) {
            userViewModel.update();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (userViewModel != null) {
                userViewModel.update();
            }
        }
    }

    public void cancelShopSuccess() {
        if (userViewModel != null) {
            userViewModel.update();
        }
    }
}
